<?php

namespace Home\Model;

use Think\Model;

class CategoryModel extends Model {

	/**
	 * 搜索分类列表
	 *
	 * @param number $where
	 * @param number $page
	 * @param string $order
	 * @param number $num
	 * @return Ambigous <number, string>
	 */
	public function search($where = 1, $page = 1, $order = '', $num = '') {
		$page = intval ( $page ) < 1 ? 1 : $page;
		$num = $num ? $num : C ( 'page_num' );

		// 读取缓存
		$cacheName = get_cache_name ( 'category_search_' . $where . $page . $order . $num );
		$result = S ( $cacheName );
		if ($result) {
			return $result;
		}

		$result ['list'] = $this->field ( 'id' )->where ( $where )->page ( $page, $num )->order ( $order )->select ();
		foreach ( $result ['list'] as $k => $v ) {
			$result ['list'] [$k] = $this->getInfo ( $v ['id'] );
		}
		$result ['total_num'] = $this->where ( $where )->count ();
		$result ['total_page'] = ceil ( $result ['total_num'] / $num );
		if ($result ['total_page'] > $page) {
			$result ['next_page'] = $page + 1;
		} else {
			$result ['next_page'] = '';
		}
		S ( $cacheName, $result, C ( 'cache_time_short' ) );
		return $result;
	}
	/**
	 * 获取单条信息
	 *
	 * @param unknown $id
	 * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, unknown, mixed, string>
	 */
	public function getInfo($id) {
		// 读取缓存
		$cacheName = get_cache_name ( 'category_' . $id );
		$result = S ( $cacheName );
		if ($result) {
			return $result;
		}

		if (intval ( $id )) {
			$where = 'id=' . intval ( $id );
		} else {
			$where = 'url="' . $id . '"';
		}
		$result = $this->where ( $where )->find ();
		if ($result ['type'] == 'article') {
			$result ['url'] = C ( 'site_url' ) . '/huahui-' . ($result ['url'] ? $result ['url'] : $result ['id']) . '/';
		} else {
			$result ['url'] = C ( 'site_url' ) . '/' . ($result ['url'] ? $result ['url'] : $result ['id']) . '/';
		}
		S ( $cacheName, $result, C ( 'cache_time_long' ) );
		return $result;
	}
}